# -*- coding: utf-8 -*-
import os
import sys

CURRENT_PATH = os.path.dirname(__file__)
sys.path.append(os.path.abspath(CURRENT_PATH + '/' + '..'))

from scpy.logger import get_logger
from config import *
from pymongo import MongoClient
from static_file.test import industry_category, find_province_city, MAPPING_LIST

MAPPING_FILE_NAME = 'A股和B股行业及地区分类_V0.3.xlsx'
# from collections import Counter
reload(sys)
sys.setdefaultencoding('utf-8')
logger = get_logger(__file__)

if CURRENT_PATH:
    CURRENT_PATH = CURRENT_PATH + "/"


def find_category_with_industry(industry):
    for key, dic in industry_category.items():
        for item in dic.keys():
            if item == industry:
                return key
            else:
                for secondKey in dic[item].keys():
                    if secondKey == industry:
                        return key
    return None


def information_addition():
    db = MongoClient(MONGO_HOST, MONGO_PORT)
    for index, item in enumerate(db['stockProj']['stockInfo'].find()):
        logger.info('No %d company %s information addition' % (index, item.get('companyName')))
        industry = item.get('industry')
        address = item.get('regAddress')
        category = find_category_with_industry(industry)
        province, city = find_province_city(address)
        item['category'] = category
        item['province'] = province
        item['city'] = city
        db['stockProj']['stockInfo'].find_one_and_update(
            {'_id': item['_id']},
            {'$set': item}
        )


def mapping_information_addtion():
    db = MongoClient(MONGO_HOST, MONGO_PORT)
    mappingList = MAPPING_LIST
    for item in mappingList:
        db['stockProj']['stockInfo'].find_one_and_update(
            {'stockCode': item['stockCode']}, {'$set': item}
        )



if __name__ == '__main__':
    # information_addition()
    mapping_information_addtion()